var basePath = CommonUtil.getPlatformPath();
var userLoginType = $("#userLoginType").val();
var courseId = $("#courseId").val();
var itemId = $("#itemId").val();
var videoResource = $("#videoResource").val();
var videoDefinition = $("#video_definition").val();
if (resource) {
  videoResource = CommonUtil.getVideoResourceByDefinition(resource, videoDefinition)
}
var videoTime = "00:00:00";
var videoJpg = $("#videoJpg").val();
var videoOrigin = $("#videoOrigin").val();
var captionUrl = $("#captionUrl").val();
var video_bullet_config = $("#video_bullet_config").val();
var videoSpeed = $("#video_speed").val();
var videoSpeedRates = [2, 1.5, 1, 0.75, 0.5];
var video_trajectory_config = $("#video_trajectory_config").val();
var jwplaySeekTimer = null;
var transcodeType = $("#transcodeType").val();
var language = $("#language").val();
var maxSeekPosition = 0;
var maxStudyPosition = parseInt($("#max_study_position").val()) || 0;
var autoPlayConfig = $("#autoPlayConfig", window.parent.document).val();
var challengeConfig = $("#challengeConfig", window.parent.document).val();
var trialDuration = parseInt($("#trialDuration").val());
var isTrialTotal = false;
var rePlayFlag = false;
var triggerRecordSave = false;
var habitSet = true;
var bulletOpenConfig = false;
$(function() {
  if (trialDuration === 0) {
    $(".tryover-container").show();
    return
  }
  document.onmousemove = mouseMove;
  var s = jwplayer.utils.isIE();
  if (s) {
    $("#video_bullet_container").remove();
    $("#bulletControl").remove()
  } else {
    $("#video_bullet_container").css({
      display: "block"
    });
    $("#bulletControl").css({
      visibility: "visible"
    })
  }
  if (videoSpeed == "0") {
    videoSpeedRates = false
  }
  $("#screen_player").width(window.innerWidth);
  videoPlayerObj.playerName = "container";
  if (video_trajectory_config == "0") {
    $("#trace_detail").hide()
  }
  if (videoJpg == "") {
    videoJpg = null
  } else {
    if (videoJpg.indexOf("http://") < 0 && videoJpg.indexOf("https://") < 0) {
      videoJpg = basePath + "/" + videoJpg
    }
  }
  var e = {};
  var t = window.innerWidth;
  var g = window.innerHeight;
  if (isLocal == "0") {
    e = {
      file: CommonUtil.formatProtocol(PlayerAutoCDN.getAvailableCdnUrl(videoResource)),
      image: videoJpg,
      autostart: !window.hasOpeningVideo(),
      playbackrates: videoSpeedRates,
      type: "flvlist",
      primary: "html5",
      width: t,
      height: g,
      controls: false,
      volume: 60
    };
    if (videoOrigin === "5") {
      e.file = videoResource
    }
  } else {
    e = {
      file: encodeURI(videoResource),
      image: videoJpg,
      autostart: true,
      playbackrates: videoSpeedRates,
      primary: "html5",
      width: t,
      height: g,
      controls: false,
      volume: 60
    }
  }
  if (language && language == "en") {
    e.language = "en-us"
  }
  if (!jwplayer.utils.isIE()) {
    var k = $("#customPlayerUrl").val();
    if (k && k != "") {
      e.servers = [k]
    }
  }
  if (captionUrl != "" && transcodeType != "1") {
    e.captions = {
      back: false,
      color: "ffffff",
      fontsize: 16
    };
    e.tracks = [{
      file: captionUrl,
      kind: "captions",
      "default": true
    }]
  }
  if (userLoginType === "0") {
    getStuBulletConfig()
  }
  if (CommonUtil.isNotEmpty(videoDefinition)) {
    if (videoDefinition != "auto") {
      e.preferlevels = [videoDefinition]
    }
  } else {
    e.preferlevels = ["240p"]
  }
  var r = null;
  var b = 0;
  var v = 0;
  var q = false;
  var d = false;
  var a = false;
  var o = {};
  var m = null;
  var f = [];
  var n = [];
  var p = "";
  var u = $("div[name^='dialog_video_ques_']");
  var c = $(parent.document).find("#vp_videoPoint").val();
  var j = $(parent.document).find("#previewType").val();
  u.each(function() {
    var w = $(this).find("input[name='insert_time']").val();
    if (p != "" && w && w != "") {
      p += "/"
    }
    p += w
  });
  if (p != null && p != "undefined" && p != "") {
    if (p.indexOf("/") > -1) {
      n = p.split("/")
    } else {
      n.push(p)
    }
  }
  o.onReady = function() {
    if (itemId !== m) {
      $.fn.showSkipVideoBeginMsg()
    }
    try {
      initWatermark("container");
      if (captionUrl !== "" && transcodeType === "1") {
        loadVideoCaption(captionUrl)
      }
    } catch (x) {
      console.log(x)
    }
    initPlayerControls();
    $("#screen_full_li").show();
    if (!$("#v_loading_ico").is(":hidden")) {
      $("#v_loading_ico").hide()
    }
    var w = setInterval(function() {
      var y = document.getElementById("container").getElementsByTagName("video")[0];
      if (y) {
        y.muted = true;
        try {
          initWatermark("container")
        } catch (z) {
          console.log(z)
        }
        clearInterval(w)
      }
    }, 10);
    try {
      if (!s && video_bullet_config == "1") {
        $.fn.videoBullet({
          userType: userLoginType,
          timePoint: v,
          pause: d,
          fullscreen: a,
          bulletOpenConfig: bulletOpenConfig
        });
        $("#slider-opacity").find("a").css({
          top: "0px"
        });
        $("#slider-speed").find("a").css({
          top: "0px"
        })
      }
    } catch (x) {}
    if (!CommonUtil.isIEBrowserNoIE11()) {
      $("#container").problemFeedBlack({
        device: "pc",
        courseId: courseId,
        itemId: itemId,
        shutdownBtnId: "pc_shut",
        isIEFlag: s
      })
    }
    initControlBarEvent("cont");
    if (habitSet && userLoginType === "0") {
      setPlayerSpeedAndSharpness("1")
    }
  }
  ;
  o.onBuffer = function(w) {
    if (jwplayer("container").getState() == "PLAYING") {
      videoPlayerObj.videoBufferLock = true
    }
    changeBtnStatusToBuffer()
  }
  ;
  o.onBufferFull = function(w) {
    videoPlayerObj.videoBufferLock = false;
    $("#definitionTip").hide();
    if (videoPlayerObj.changeVideoLevelPause) {
      videoPlayerObj.changeVideoLevelPause = false
    }
    changeBtnStatusToPlayingOrBufferFull()
  }
  ;
  o.onPlay = function() {
    $("#video-rt").show();
    if (habitSet && userLoginType === "0") {
      habitSet = false;
      setTimeout(function() {
        setPlayerSpeedAndSharpness("1")
      }, 600)
    }
    if (!s) {
      d = false
    }
    var x = document.getElementById("container").getElementsByTagName("video")[0];
    if (x && x.muted === true) {
      x.muted = false
    }
    var w = videoPlayerObj.isGetVideoRecord;
    if (w) {
      videoPlayerObj.isGetVideoRecord = false;
      addQualityLevels();
      if (userLoginType == "0") {
        judgeVideoIsReady()
      }
    }
    changeBtnStatusToPlayingOrBufferFull();
    if (jwplayer("opening-video-container") != null) {
      window.hasOpeningVideo() && this.pause()
    }
    if (window.parent.parent.continueStart != undefined && window.parent.parent.continueStart) {
      v = this.getPosition();
      this.pause();
      window.parent.parent.continueStart = false
    }
  }
  ;
  o.onPause = function() {
    if (!s) {
      d = true;
      if (d && video_bullet_config == "1") {
        try {
          $.fn.videoBullet({
            timePoint: v,
            pause: d,
            fullscreen: a,
            bulletOpenConfig: bulletOpenConfig
          })
        } catch (w) {}
      }
    }
    changeBtnStatusToPauseOrReplay()
  }
  ;
  o.onTime = function() {
    b = jwplayer("container").getDuration();
    if (b && b > 0) {
      if (trialDuration === -2) {
        isTrialTotal = true;
        trialDuration = b;
        getPurchasePath(trialDuration, "video")
      }
      if (rePlayFlag) {
        rePlayFlag = false;
        v = 0
      }
      if (!isTrialTotal && trialDuration !== -1 && v > trialDuration) {
        this.pause();
        $(".tryover-container").show();
        return
      }
      var y = b - v;
      if (y <= 10 && y > 9) {
        $.fn.showSkipVideoEndMsg()
      }
      if (top.isTimerStop || videoPlayerObj.questionInsertPause) {
        this.pause();
        return
      }
      if (videoPlayerObj.changeVideoLevelPause) {
        videoPlayerObj.changeVideoLevelPause = false
      }
      if (jwplayer("container").getState() == "PLAYING") {
        v = this.getPosition();
        if (captionUrl != "" && transcodeType == "1") {
          updateCurCaptionText(v)
        }
      }
      if (videoPlayerObj.isInitPosProgress) {
        videoPlayerObj.isInitPosProgress = false;
        connectionPlayAddCompleteDiv(videoPlayerObj.learningVideoTime, "container")
      }
      b = parseInt(b);
      videoTime = CommonUtil.convertTotalSeconds(b);
      ResourceUtils.updateVideoTotalTime(itemId, videoTime);
      var C = v / b * 100;
      if (!videoPlayerObj.moveLock) {
        if (C > 99.5) {
          C = 99.5
        }
        if (C <= 0.5) {
          C = 0.5
        }
        $("#pos_btn").css("left", C + "%");
        $("#pos_btn_width").css("width", C + "%");
        maxSeekPosition = Math.max(maxSeekPosition, Math.max(v, maxStudyPosition))
      }
      var B = videoPlayerObj.startPos || 0;
      $("#" + videoPlayerObj.tempId).css("width", (C - B) + "%");
      $("#screen_player_time_1").text(CommonUtil.convertTotalSecondsHMS(v));
      $("#screen_player_time_2").text(CommonUtil.convertTotalSecondsHMS(b));
      $.fn.videoLearnRecord({
        playComplete: false,
        courseId: courseId,
        itemId: itemId,
        position: v,
        videoTotalTime: videoTime
      });
      if (r == null) {
        var A = 300;
        if (b <= A) {
          A = parseInt(b * 0.8)
        }
        r = setInterval(function() {
          $.fn.videoLearnRecord({
            interval: true,
            playComplete: false,
            courseId: courseId,
            itemId: itemId,
            position: v,
            videoTotalTime: videoTime
          })
        }, A * 1000)
      }
      if ($("#video_trace_container").is(":hidden")) {
        $("#video_trace_container").show()
      }
      if (!s && video_bullet_config == "1") {
        $.fn.videoBullet({
          userType: userLoginType,
          timePoint: v,
          pause: d,
          fullscreen: a,
          bulletOpenConfig: bulletOpenConfig
        })
      }
    }
    if (n && n.length > 0 && userLoginType === "0") {
      var x = (v != null && v != "undefined") ? v.toString().split(".")[0] : 0;
      for (var z = 0; z < n.length; z++) {
        if (parseFloat(n[z]) - parseFloat(x) == 0) {
          this.pause();
          this.setFullscreen(false);
          var w = $("div[name='dialog_video_ques_" + x + "']").find("input[name='itemQuestionBean.id']").val();
          insert_question(w);
          n.splice(z, 1);
          $("#div_layer_q").show();
          videoPlayerObj.questionInsertPause = true
        }
      }
    }
    if ((b * 0.8) <= v && !triggerRecordSave) {
      triggerRecordSave = true;
      $.fn.videoLearnRecord({
        interval: true,
        playComplete: false,
        courseId: courseId,
        itemId: itemId,
        position: v,
        videoTotalTime: videoTime
      })
    }
  }
  ;
  o.onComplete = function() {
    q = true;
    if (r) {
      clearInterval(r)
    }
    if (b && b > 0) {
      var w = this.getPosition();
      $.fn.videoLearnRecord({
        playComplete: true,
        async: false,
        courseId: courseId,
        itemId: itemId,
        position: w,
        videoTotalTime: videoTime
      })
    }
    window.playEndingAdVideo();
    if (challengeConfig && challengeConfig === "1") {
      if ($("#s_point_" + itemId, window.parent.document).find(".challenge ").length > 0) {
        MultiPageEventBus.emit("play-end-event", {
          itemId: itemId,
          courseId: courseId
        });
        MultiPageEventBus.on("lock-item-end-event", function(y) {
          var x = window.parent.getNextNode(itemId);
          if (y === "1" && x) {
            autoLearn()
          }
        })
      } else {
        autoLearn()
      }
    } else {
      autoLearn()
    }
    changeBtnStatusToPauseOrReplay()
  }
  ;
  o.onFullscreen = function(x) {
    if (!s && video_bullet_config == "1") {
      if (x.fullscreen) {
        a = true
      } else {
        a = false
      }
      try {
        $.fn.videoBullet({
          timePoint: v,
          pause: d,
          fullscreen: a,
          bulletOpenConfig: bulletOpenConfig
        })
      } catch (w) {}
    }
  }
  ;
  e.events = o;
  jwplayer("container").setup(e);
  var h = videoPlayerObj.playerName;
  if (videoPlayerObj.videoType == "video_video") {
    h = videoPlayerObj.coursewarePlayerName
  }
  jwplayer(h).setVolume(50);
  if (userLoginType == "0") {
    var l = new $.connectionPlay({
      courseId: courseId,
      setItem: function() {
        if (itemId == null || itemId == "" || itemId == undefined) {
          itemId = null
        }
        return itemId
      },
      setVideoTime: function() {
        return v
      }
    });
    if (c != "" && c != null && c != undefined) {
      l.connTime = c;
      l.connItem = $(parent.document).find("#vp_itemId").val()
    }
    var i = parseInt(l.connTime, 10);
    m = l.connItem;
    $.fn.getLastPlayPosition(itemId).then(function(w) {
      if (itemId === l.connItem) {
        w = w < 0 ? i : w
      }
      w = j && j === "previewUnknown" ? c : w;
      if (w > 0 && isLocal === "0") {
        videoPlayerObj.isInitPosProgress = true;
        videoPlayerObj.learningVideoTime = w;
        jwplayer("container").seek(w)
      } else {
        if (w > 0 && isLocal === "1") {
          jwplaySeekTimer = setInterval(function() {
            playSeek(w)
          }, 200)
        }
      }
      if (w > 0) {
        var x = CommonUtil.millisecondToTime(w * 1000);
        if (!j) {
          if (trialDuration === -1) {
            setTimeout(function() {
              $.fn.playerMsg({
                msg: "已为你定位到上次学习位置:" + x,
                containerId: "container",
                location: "leftLower",
                time: 3000,
                isNeedMoveUp: false
              })
            }, 2000)
          } else {
            setTimeout(function() {
              $.fn.playerMsg({
                msg: "已为你定位到上次学习位置:" + x,
                containerId: "container",
                location: "leftLower",
                time: 3000,
                isNeedMoveUp: true
              })
            }, 2000)
          }
        }
      }
    })
  }
  if ((userLoginType == "1" || userLoginType == "3") && c != "" && c != null && c != undefined) {
    var l = new $.connectionPlay({
      courseId: courseId,
      setItem: function() {
        return $(parent.document).find("#vp_itemId").val()
      },
      setVideoTime: function() {
        return c
      }
    });
    l.connTime = c;
    l.connItem = $(parent.document).find("#vp_itemId").val();
    var i = parseInt(l.connTime, 10);
    if (itemId == l.connItem) {
      if (i > 0 && isLocal == "0") {
        jwplayer("container").seek(i)
      } else {
        if (i > 0 && isLocal == "1") {
          jwplaySeekTimer = setInterval(function() {
            playSeek(i)
          }, 200)
        }
      }
    }
  }
  $(parent.document).find("#vp_videoPoint").val("");
  $(parent.document).find("#vp_pId").val("");
  $(parent.document).find("#vp_itemId").val("");
  questionInsertInitBtn();
  videoPlayerObj.videoType = "video";
  $(window).unload(function() {
    if (!q && b && b > 0 && videoTime != "00:00:00") {
      $.fn.videoLearnRecord({
        unloadVideoPage: true,
        async: false,
        courseId: courseId,
        itemId: itemId,
        position: v,
        videoTotalTime: videoTime
      })
    }
  });
  $(window).resize(function() {
    var w = window.innerWidth;
    var x = window.innerHeight;
    $("#container").width(w);
    $("#container").height(x);
    $("#video_bullet_container").width(w);
    $("#video_bullet_container").height(x);
    $("#screen_player").width(window.innerWidth);
    setTimeout(function() {
      btnResize()
    }, 10)
  });
  btnResize();
  tipShowOrHide();
  $("#bullet_recordList_1").mCustomScrollbar();
  $(window).focus();
  $("html body", parent.document).attr("style", "background: #ffffff");
  MultiPageEventBus.on("seek-position-event", function(w) {
    if (w && w.time && jwplayer("container")) {
      try {
        jwplayer("container").seek(CommonUtil.timeToSeconds(w.time))
      } catch (x) {
        console.log(x)
      }
    }
  })
});
function autoLearn() {
  if (jwplayer("ending-video-container") == null) {
    if (autoPlayConfig === "1") {
      if ($("#screen_full").find(".icon-restore-stroke").length > 0) {
        $("#screen_full").click()
      }
      if (typeof (window.parent.exePlayNextNode) == "function") {
        window.parent.exePlayNextNode(itemId)
      }
    }
  } else {
    setTimeout(autoLearn, 800)
  }
}
function playSeek(a) {
  var c = jwplayer("container").getState();
  if (c != undefined && c.toLocaleUpperCase() == "PLAYING") {
    jwplayer("container").seek(a);
    var b = jwplayer("container").getPosition();
    if (b > 0 && jwplaySeekTimer != null) {
      clearInterval(jwplaySeekTimer)
    }
  }
}
function rePlay() {
  rePlayFlag = true;
  $(".tryover-container").hide();
  jwplayer("container").seek(0)
}
function questionInsert() {
  $(".popup-content-in").mCustomScrollbar({
    scrollbarPosition: "outside",
    theme: "my-theme"
  })
}
function btnResize() {
  var f = $("#container").height();
  if (f == null || f == undefined || f == "") {
    f = $("body").height()
  }
  var a = $("body").width();
  var b = $("#player_pause").width();
  var e = $("#player_pause").height();
  $("#player_pause").css({
    top: (f - e) / 2,
    left: (a - b) / 2
  });
  var d = $("#v_loading_ico").width();
  var c = $("#v_loading_ico").height();
  $("#v_loading_ico").css({
    top: (f - c) / 2,
    left: (a - d) / 2
  })
}
function tipShowOrHide() {
  $("#shutdown").click(function() {
    $("#definitionTip").hide()
  })
}
function mouseMove(e) {
  e = e || window.event;
  var b = mouseCoords(e);
  var c = b.x;
  var a = e.pageY;
  var d = $(window).height() - a;
  var g = $(".learn-menu", top.document).attr("canHide");
  var f = parseInt($(".learn-menu", top.document).css("left"));
  if (g == "yes") {
    if (f < 0 && c < 10 && d > 120) {
      $(".learn-menu", top.document).css("left", 0)
    } else {
      $(".learn-menu", top.document).css("left", -64)
    }
  }
}
function mouseCoords(a) {
  if (a.pageX) {
    return {
      x: a.pageX
    }
  }
  return {
    x: a.clientX + document.body.scrollLeft - document.body.clientLeft
  }
}
function setPlayerSpeedAndSharpness(i) {
  try {
    var k = $("#video_speed").val();
    var f = $("#loginId").val();
    var d = localStorage.getItem(f + "_speed_sharpness_habit");
    if (d && f) {
      var b = JSON.parse(d);
      var h = b.speedVal;
      if (h && parseFloat(h) < 3 && k && k === "1") {
        var l = $("#li_speed li[name='speed'][speedval='" + h + "']");
        if (l && l.length === 1 && i === "0") {
          $("#li_speedval_cur").text($(l[0]).find("a").text())
        } else {
          if (l && l.length === 1 && i === "1") {
            setPlaybackRate($(l[0]))
          }
        }
      }
      if (videoResource.indexOf("VIDEOSEGMENTS/meta.json") > 0) {
        var o = b.definitionVal;
        if (o !== undefined && o !== "") {
          var m = $("#li_definition li[name='definition'][definitionval='" + o + "']");
          if (m && m.length === 1 && i === "0") {
            var a = videoPlayerObj.playerName;
            var p = jwplayer(a).getQualityLevels();
            var j = p[o].label;
            if (j === "音频") {
              return
            }
            $("#li_definition_cur").text(j);
            $("#li_definition_cur").show();
            $("#tipValue").html("[" + j + "]");
            $("#definitionTip").show()
          } else {
            if (m && m.length === 1 && i === "1") {
              $(m[0]).click()
            }
          }
        }
      } else {
        var n = b.qualityVal;
        if (n !== undefined && n !== "") {
          var c = $("#li_definition_ul li.choose-items-cell[vkey='" + n + "']");
          if (c && c.length === 1 && i === "0") {
            $(c).find("a").addClass("cur-data");
            $("#li_definition_cur").text($(c).text())
          } else {
            if (c && c.length === 1 && i === "1") {
              reloadPlayer($(c[0]))
            }
          }
        }
      }
    }
  } catch (g) {
    console.log("设置默认使用习惯失败！", g)
  }
}
function getStuBulletConfig() {
  try {
    var b = $("#loginId").val();
    var c = localStorage.getItem(b + "_speed_sharpness_habit");
    if (c && b) {
      var a = JSON.parse(c);
      var f = a.bulletConfig;
      bulletOpenConfig = f && f === "1"
    }
  } catch (d) {
    console.log("设置默认使用习惯失败！", d)
  }
}
;
